import React, { useEffect, useState } from 'react';
import Router, { withRouter } from '@/router/renderRouter';
import moment from 'moment';
import { Row, Col, message, Card, InputNumber, Input, Radio, Button, DatePicker, Spin } from 'antd';
import { systemSettingSave, systemSettingInfo } from '@/api/api.js';
import './index.scss';

const SystemSetting = (props) => {
  const [settingInfoInit, setSettingInfoInit] = useState({})
  const [settingInfo, setSettingInfo] = useState({})
  const [loading, setloading] = useState(false)
  const [saveloading, setsaveloading] = useState(false)
  
  const options = [
    { label: '开启', value: 'true' },
    { label: '关闭', value: 'false' },
  ];
  const options1 = [
    { label: '开启', value: '1' },
    { label: '关闭', value: '0' },
  ];
  
  const get = async () => {
    try {
      setloading(true)
      let res = await systemSettingInfo();
      if (res.code === 0) {
        let obj = {};
        res.data.forEach(item=>{
          obj[item.code] = item.value;
        })
        setSettingInfo(obj)
        console.log(obj,'setSettingInfo');
        setSettingInfoInit(res.data)
      }
      setloading(false)
    } catch (error) {
      console.log(error)
    }
  };
  const reset = () => {
    let obj = {};
    settingInfoInit.forEach(item=>{
      obj[item.code] = item.value;
    })
    setSettingInfo(obj)
  };
  const setValue = (value,code) => {
    let obj = JSON.parse(JSON.stringify(settingInfo));
    obj[code] = value;
    setSettingInfo(obj);
  };
  const onChange = (value) => {
    console.log(value)
  };
  const save = async () => {
    try {
      setsaveloading(true)
      let obj = []
      settingInfoInit.forEach(item=>{
        if(item.value !== settingInfo[item.code]){
          obj.push({
            "name": item.name,
            "code": item.code,
            "value": settingInfo[item.code]
          })
        }
      })
      if(obj.length === 0){
        message.warning("当前页没有修改")
      }else{
        let res = await systemSettingSave(obj);
        if (res.code === 0 && res.data === true) {
          message.success("修改成功")
          get();
        }
      }
      setsaveloading(false)
    } catch (error) {
      console.log(error)
    }
  };
  
  const addAct = (aValue=0,bValue=0) => {
    let sum = 0;
    aValue = aValue.toString()
    bValue = bValue.toString()
    let aLength = aValue.indexOf('.') !== -1 ? aValue.split('.')[1].length : 0;
    let bLength = bValue.indexOf('.') !== -1 ? bValue.split('.')[1].length : 0;
    if(aLength > bLength){
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(aLength)
      console.log(aLength)
    }else{
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(bLength)
    }
    return sum;
  };
  
  
  // 初始化
  useEffect(() => {
    get()
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
    
    
  return (
    <>
      <div className="content">
        <Spin spinning={loading}>
          <Row gutter={16}>
            <Col span={11}>
              <Card title="风控设置" bordered={false}>
                <div className="form1">
                  <label>修改金额需要交易密码:</label>
                  <Radio.Group className="radio" options={options} onChange={(e)=>{setValue(e.target.value,'UPDATE_AMOUNT_TRANS_PWD')}} value={settingInfo['UPDATE_AMOUNT_TRANS_PWD']} />
                </div>
                <div className="form1">
                  <label>是否开启登录设备检验:</label>
                  <Radio.Group className="radio" options={options} onChange={(e)=>{setValue(e.target.value,'IS_OPEN_LOGIN_DEVICE_CHECK')}} value={settingInfo['IS_OPEN_LOGIN_DEVICE_CHECK']} />
                </div>
                <div className="form1">
                  <label>是否开启人脸识别:</label>
                  <Radio.Group className="radio" options={options} onChange={(e)=>{setValue(e.target.value,'IS_OPEN_FACE_RECOGNITION')}} value={settingInfo['IS_OPEN_FACE_RECOGNITION']} />
                </div>
                <div className="form1">
                  <label>系统自动锁定登录密码连续错误次数:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'SYS_CONTINUOUS_ERROR_LOGIN_TIMES')}} value={settingInfo['SYS_CONTINUOUS_ERROR_LOGIN_TIMES']} />
                </div>
                <div className="form1">
                  <label>系统自动锁定交易密码连续错误次数:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'SYS_CONTINUOUS_ERROR_TRANS_TIMES')}} value={settingInfo['SYS_CONTINUOUS_ERROR_TRANS_TIMES']} />
                </div>
              </Card>
              <div className="line"></div>
              <Card title="USDT汇率设置" bordered={false}>
                <div className="form3">
                  <label>商户USDT买币汇率差:</label>
                  <InputNumber className="input" onChange={(e)=>{setValue(e,'USDT_BUY_NUMBER_RATE_DEFF')}} value={settingInfo['USDT_BUY_NUMBER_RATE_DEFF']} />
                  <span>(实时汇率：{addAct(settingInfo['USDT_REAL_TIME_EXCHANGE_RATES'],settingInfo['USDT_BUY_NUMBER_RATE_DEFF'])})</span>
                </div>
                <div className="form3">
                  <label>商户USDT卖币汇率差:</label>
                  <InputNumber className="input" onChange={(e)=>{setValue(e,'USDT_SELL_NUMBER_RATE_DEFF')}} value={settingInfo['USDT_SELL_NUMBER_RATE_DEFF']} />
                  <span>(实时汇率：{addAct(settingInfo['USDT_REAL_TIME_EXCHANGE_RATES'],settingInfo['USDT_SELL_NUMBER_RATE_DEFF'])})</span>
                </div>
                <div className="form3">
                  <label>会员USDT买币汇率差:</label>
                  <InputNumber className="input" onChange={(e)=>{setValue(e,'MEMBER_USDT_BUY_NUMBER_RATE_DEFF')}} value={settingInfo['MEMBER_USDT_BUY_NUMBER_RATE_DEFF']} />
                  <span>(实时汇率：{addAct(settingInfo['USDT_REAL_TIME_EXCHANGE_RATES'],settingInfo['MEMBER_USDT_BUY_NUMBER_RATE_DEFF'])})</span>
                </div>
                <div className="form3">
                  <label>USDT实时汇率:</label>
                  <InputNumber className="input" onChange={(e)=>{setValue(e,'USDT_REAL_TIME_EXCHANGE_RATES')}} value={settingInfo['USDT_REAL_TIME_EXCHANGE_RATES']} />
                </div>
              </Card>
            </Col>
            <Col span={12}>
              <Card title="基础设置" bordered={false}>
                <div className="form1">
                  <label>是否开启维护页:</label>
                  <Radio.Group className="radio" options={options} onChange={(e)=>{setValue(e.target.value,'IS_OPEN_MAINTENANCE_PAGE')}} value={settingInfo['IS_OPEN_MAINTENANCE_PAGE']} />
                </div>
                <div className="form1">
                  <label>维护页结束时间:</label>
                  <DatePicker className="input" showTime onOk={(e)=>{setValue(moment(e).format('YYYY-MM-DD HH:mm:ss'),'MAINTENANCE_PAGE_END_TIME')}} value={moment(settingInfo['MAINTENANCE_PAGE_END_TIME'])} />
                </div>
                <div className="form1">
                  <label>在线客服地址(官网):</label>
                  <Input className="input" onChange={(e)=>{setValue(e.target.value,'ONLINE_CUSTOMER_SERVICE_WEBSITE')}} value={settingInfo['ONLINE_CUSTOMER_SERVICE_WEBSITE']} />
                </div>
                <div className="form1">
                  <label>是否开启万能验证码:</label>
                  <Radio.Group className="radio" options={options} onChange={(e)=>{setValue(e.target.value,'ENABLE_UNIVERSAL_CAPTCHA')}} value={settingInfo['ENABLE_UNIVERSAL_CAPTCHA']} />
                </div>
                <div className="form1">
                  <label>是否开启滑动验证码:</label>
                  <Radio.Group className="radio" options={options1} onChange={(e)=>{setValue(e.target.value,'CAPTCHA_CODE_OPEN')}} value={settingInfo['CAPTCHA_CODE_OPEN']} />
                </div>
              </Card>
              <div className="line"></div>
              <Card title="交易规则设置" bordered={false}>
                <div className="form1">
                  <label>用户取消交易次数:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'USER_CANCELED_TRANS_NUMBER')}} value={settingInfo['USER_CANCELED_TRANS_NUMBER']} />
                </div>
                <div className="form1">
                  <label>卖家N分钟内不确认交易:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'SELLER_MINUTES_UNSURE_ABOUT_TRANS')}} value={settingInfo['SELLER_MINUTES_UNSURE_ABOUT_TRANS']} />
                </div>
                <div className="form1">
                  <label>卖家N分钟内未放币:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'SELLER_MINUTES_UNSURE_NOT_RELEASE')}} value={settingInfo['SELLER_MINUTES_UNSURE_NOT_RELEASE']} />
                </div>
                <div className="form1">
                  <label>买家N分钟内不转账:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'BUYER_MINUTES_UNSURE_NOT_TRANS')}} value={settingInfo['BUYER_MINUTES_UNSURE_NOT_TRANS']} />
                </div>
              </Card>
              <div className="line"></div>
              <Card title="首页成交数据" bordered={false}>
                <div className="form1">
                  <label>24小时交易量:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'ONE_DAY_TRANS_NUMBER')}} value={settingInfo['ONE_DAY_TRANS_NUMBER']} />
                </div>
                <div className="form1">
                  <label>24小时成交单:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'ONE_DAY_TRANS_ORDER')}} value={settingInfo['ONE_DAY_TRANS_ORDER']} />
                </div>
                <div className="form1">
                  <label>交易成功率:</label>
                  <InputNumber className="input" min={0} onChange={(e)=>{setValue(e,'TRANS_SUCCESS_FEE')}} value={parseFloat(settingInfo['TRANS_SUCCESS_FEE'])} />
                  <span>%</span>
                </div>
              </Card>
            </Col>
          </Row>
          <div className="btns">
            <Button type="primary" loading={saveloading} onClick={()=>{save()}}>保存</Button>
            <Button style={{marginLeft: '20px'}} onClick={()=>{reset()}}>还原</Button>
          </div>
        </Spin>
      </div>
    </>
  )
}
export default withRouter(SystemSetting)